import { observable, action, toJS } from "mobx";
import { Tools, Modal, Bubble } from "weaver-mobile";
import {
  Form,
  Comment,
  Reply,
  SearchAdvanced,
  CKRichText,
  AtSomeone,
  BrowserHrm,
} from "weaver-mobile-page";

import * as Api from "../../api/CommunicationApi";

const alert = Modal.alert;
const getLabel = Tools.getLabel;

const createParams = {
  createLoading: true,
  topKey: "basic",
  params_fileds: {
    task: [], // 相关任务
    customer: [], // 相关客户
    workFlow: [], // 相关流程
    document: [], // 相关文档
    uploadFile: [], // 相关附件
    project: [], // 相关项目
  },
};

export default class DetailStore {
  @observable path = "";
  @observable coworkId = null;
  @observable floor = ""; // 楼层号
  @observable isLoading = true;
  @observable page = ""; // 当前页面
  @observable replyType = "";
  @observable viewRight = null; // 查看权限
  @observable approvalAtatus = null; // 是否审批
  @observable detailHeader = {}; // 相关交流头部信息
  @observable itemsVO = {}; // 协作信息
  @observable fixTop = false;
  @observable coworkStatus = "1"; //协作状态
  @observable isAnonymous = ""; //是否允许匿名
  @observable placeholderValue = getLabel(390700, "交流内容"); //reply组件的输入框预期值
  @observable defaultShowInfo = []; // 默认展开详情

  @observable isImportant = false; // 是否星标
  @observable isHeart = false; // 是否收藏
  @observable communicateReply = new Reply.Store({
    getAttachList: this.getReplyAttachList /* getAtConfig: this.getAtConfig */,
  }); // 详情页面入口Reply
  @observable atSomeOne;
  @observable invitedBrowser;
  @observable invitedValueArray = [];
  @observable atSomeOneDatas = [];
  @observable communicateReplyVisible = null;
  @observable outReplyVisible = true; // 详情页面入口Reply组件显隐情况
  @observable replyDatas = {}; // reply 组件+号内部回显数据

  @observable loading = true;
  @observable relatedPage = 1; // 请求参数  (交流详情所处页数)
  @observable recordType = "common";
  @observable relatedComment;
  @observable relatedAdSearch;
  @observable replyVisible = null; // 回复组件的显隐控制
  @observable replyComment = null; // 点击的源数据
  @observable replyCommentParent = null; // 点击事件的父级数据
  @observable detailReply = new Reply.Store({
    getAttachList: this.getReplyAttachList,
  }); // 回复评论Store
  @observable hasMore = true; // 是否含有下一页
  @observable over = ""; // 协作超期

  @observable quoteReply = new Reply.Store({
    getAttachList: this.getReplyAttachList,
  });
  @observable commentReplyStoreMap = {};
  @observable quoteReplyStoreMap = {};
  @observable partersMap = {}; //参与情况
  @observable resourceMap = {}; //相关资源
  @observable isCoworkHiddened = "";
  @observable routePath = null;
  /* 与我相关 */
  @observable relatedMeComment = new Comment.Store({
    // 与我相关列表请求
    getComment: this.relatedMe,
    operate: this.detailOperate,
  });

  photoArr = []; // 展示详情图片集合
  @observable imagrArr = []; // 发表交流或回复时候选择的图片集合

  /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!    CreateStore   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
  @observable id = null; //当前页面的协作ID
  @observable createPage = 0; // 当前Tab页指向
  @observable topKey = createParams.topKey;
  @observable createLoading = createParams.createLoading;
  @observable addInfoForm = new Form.Store({
    route: "/communication/createCowork",
  }); // 基本信息表单内容
  @observable endDate = "";
  @observable coworkText = ""; // 新建协作页面内容渲染
  @observable uploadUrl = "/api/cowork/base/uploadOperate"; // 附件上传url
  // @observable reply = new Reply.Store({ getAttachList: this.getCreateAttachList });
  // @observable createRichText = new CKRichText.Store({ reply: { getAttachList: ()=>this.getCreateAttachList() } });
  @observable createRichText = null;
  @observable itemsVORemark = ""; // 存放编辑初始富文本内容
  @observable itemsVo = { typeid: "" }; //协作对象属性
  @observable coworkTypeInfoMap = {};
  @observable createRoutePath = null;
  @observable typeId = this.itemsVo.typeid;
  @observable editTypeId = "";
  @observable accessoryPath = {}; //版块对应的绑定的附件目录等信息
  @observable params_fileds = createParams.params_fileds;
  @observable createDisabled = false; // 防止重复提交
  @observable currentModel = {}; //当前对话框弹窗
  /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
  @action setStoreState = (params) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
  };

  inital = () => {
    this.atSomeOne = new AtSomeone.Store({ route: this.path, id: "at" });
    this.invitedBrowser = new BrowserHrm.Store({
      route: this.path,
      id: "invitedHrm",
    });
    this.initalAdSearch();
    this.coworkDiscussSearchCondition();
    this.getShareConditionStrList("all");
    this.getCoworkDiscussData();
  };

  /* *************************协作详情**************************** */
  // 头部信息请求
  @action viewCowork = (v, isRefresh = false) => {
    this.isLoading = true;
    this.photoArr = [];
    this.relatedPage = 1;
    let params = {
      coworkId: this.coworkId,
    };
    Api.viewCowork(params).then(
      action("fetchSuccess", (data) => {
        this.viewRight = data.viewRight;
        if (data.viewRight > 0) {
          // 有权限查看
          this.detailHeader = data;
          this.over = data.over;
          this.isCoworkHiddened = this.detailHeader.isCoworkHiddened;
          this.itemsVO = this.detailHeader.itemsVO;
          this.coworkStatus = this.detailHeader.itemsVO.status;
          this.isAnonymous = this.detailHeader.itemsVO.isAnonymous;
          this.defaultShowInfo = data.itemsVO.itemstate == "1" ? ["0"] : [];
          let coworkId = this.itemsVO.id || "";
          if (!isRefresh) {
            this.inital(v);
            this.getAtConfig({ coworkId });
          }
          if (data.itemsVO.remark.indexOf("<img") > -1) {
            // 头部内容有图片
            toJS(data.itemsVO.remark.split("<img")).map((imgs) => {
              let imgSrc =
                imgs.match(/src="(\S*)"/) && imgs.match(/src="(\S*)"/)[1];
              let imgId =
                imgs.match(/data_id='(\S*)'/) &&
                imgs.match(/data_id='(\S*)'/)[1];
              return (
                imgSrc &&
                imgId &&
                this.photoArr.push({ url: imgSrc, imgId: imgId })
              );
            });
          }
          this.approvalAtatus = data.itemsVO.approvalAtatus;
          this.coworkText = data.itemsVO.remark;
          this.itemsVORemark = data.itemsVO.remark;
          this.isImportant = data.isCoworkImportant;
          this.editTypeId = data.itemsVO.typeid;
        }
        this.isLoading = false;
      })
    );
  };

  // @请求
  @action getAtConfig = (params) => {
    Api.atList(params).then((res) => {
      this.atSomeOneDatas = res.operators
        ? res.operators.map((ops) => {
            let newOne = {
              name: ops.data,
              id: ops.uid,
              imgSrc: ops.messagerUrl,
            };
            return newOne;
          })
        : [];
    });
  };

  initalAdSearch = () => {
    this.relatedAdSearch = new SearchAdvanced.Store({
      route: this.path,
      id: "discussSearch",
    }); // 相关交流高级搜索
  };

  /* ***********************************相关交流************************************** */
  @action initComment = () => {
    // 相关交流列表请求
    this.relatedComment = new Comment.Store({
      getComment: this.discussRecord,
      operate: this.detailOperate,
    });
  };

  @action("相关交流列表请求")
  discussRecord = () => {
    this.loading = true;
    const relatedAdSearchParams = this.relatedAdSearch.form.formParams || {};
    let params = {
      coworkId: this.coworkId,
      recordType: "common",
      currentPage: this.relatedPage++,
      srchFloorNum: this.floor,
      isShowApproval: "",
      ...relatedAdSearchParams,
    };
    return Api.discussRecord(params).then(
      action("fetchSuccess", (res) => {
        this.hasMore = res.hasMore;
        this.loading = false;
        return res;
      })
    );
  };

  @action("点击加载下一页")
  getNextPageDatas = (callback) => {
    if (this.page === "relatedCommunication") {
      this.relatedComment.getNextPageDatas(); // 刷新列表重新渲染数据
    } else {
      this.relatedMeComment.getNextPageDatas();
    }
    if (callback) callback();
  };

  @action("相关交流高级搜索")
  coworkDiscussSearchCondition = (params) => {
    this.relatedAdSearch
      .getData({
        url: `/api/cowork/view/getDiscussRecordCondition`,
        method: `GET`,
        params: { ...params },
      })
      .then((form) => {
        this.floor && form.updateField("srchFloorNum", this.floor);
      });
  };

  @action("高级搜索事件处理")
  onRelatedAdSearch = () => {
    this.relatedPage = 1;
    if (this.page === "relatedCommunication") {
      this.relatedComment.getDatas(); // 刷新列表重新渲染数据
    } else {
      this.relatedMeComment.getDatas();
    }
  };

  @action
  onReset = () => {
    this.relatedAdSearch.form.resetFields();
    if (this.floor) {
      this.relatedAdSearch.form.updateField("srchFloorNum", this.floor);
    }
  };

  @action("评论组件的操作")
  detailOperate = (params) => {
    let tempState = this.fixTop;
    const {
      data,
      parent,
      type: { key, type },
    } = params;
    this.replyComment = data;
    this.replyCommentParent = parent;
    if (type === "fabulous") {
      // 点赞
      this.coworkDiscussOperation(data, parent, "agree");
    } else if (type === "reply" || key === "comment") {
      // 评论
      this.fixTop = tempState;
      this.replyType = "comment";
      this.placeholderValue = getLabel(18540, "回复") + " " + data.creater.name;
      if (!this.commentReplyStoreMap[data.replyId]) {
        this.commentReplyStoreMap[data.replyId] = new Reply.Store({
          getAttachList: this.getReplyAttachList,
        });
        this.commentReplyStoreMap[data.replyId].doInit();
      }
      // this.replyVisible(true);
      this.outReplyVisible = false;
      this.communicateReplyVisible(true);
    } else if (type === "quote") {
      // 引用---------------------待更改
      this.replyType = "quote";
      this.placeholderValue = getLabel("19422", "引用");
      if (!this.quoteReplyStoreMap[data.replyId]) {
        this.quoteReplyStoreMap[data.replyId] = new Reply.Store({
          getAttachList: this.getReplyAttachList,
        });
        this.quoteReplyStoreMap[data.replyId].doInit();
      }
      this.outReplyVisible = false;
      this.communicateReplyVisible(true);
    } else if (type === "delete") {
      // 删除
      //交流的删除
      if (key === "delDiscuss") {
        this.currentModel = alert(
          getLabel(390724, "确认要删除该讨论记录"),
          "",
          [
            {
              text: getLabel(390722, "只删除该帖子"),
              onPress: () => {
                this.coworkDiscussOperation(data, parent, "delDiscuss", "", {
                  isDeleteAll: 0,
                });
              },
            },
            {
              text: getLabel(390721, "同时删除该帖子的所有评论"),
              onPress: () => {
                this.coworkDiscussOperation(data, parent, "delDiscuss", "", {
                  isDeleteAll: 1,
                });
              },
            },
            { text: getLabel(31129, "取消") },
          ]
        );
        //评论的删除
      } else if (key === "delComment") {
        this.currentModel = alert(getLabel(388758, "确认要删除吗？"), "", [
          { text: getLabel(31129, "取消") },
          {
            text: getLabel(33703, "确认"),
            onPress: () => {
              this.coworkDiscussOperation(data, parent, "delComment");
            },
          },
        ]);
      }
    } else if (key === "dotop") {
      // 置顶
      this.relatedPage = 1;
      this.coworkDiscussOperation(
        data,
        parent,
        "dotop",
        this.page === "relatedCommunication"
          ? this.relatedComment.getDatas
          : this.relatedMeComment.getDatas
      );
    } else if (key === "canceltop") {
      // 取消置顶
      this.relatedPage = 1;
      this.coworkDiscussOperation(
        data,
        parent,
        "canceltop",
        this.page === "relatedCommunication"
          ? this.relatedComment.getDatas
          : this.relatedMeComment.getDatas
      );
    } else if (key === "doApproveDiscuss") {
      // 批准
      this.coworkDiscussOperation(data, parent, "doApproveDiscuss");
    } else if (key === "edit") {
      // 编辑
      this.replyType = "reply";
      this.outReplyVisible = false;
      this.communicateReplyVisible(true);
    }
  };

  @action
  onMaskClick = () => {
    this.replyType = "";
  };

  @action("协作-协作交流-置顶/取消置顶/审批/收藏/删除评论/赞 交流记录")
  coworkDiscussOperation = (data, parent, val, callback, otherparams) => {
    let params = {
      id: data.replyId,
      coworkId: data.coworkId,
      operationType: val,
      discussId: parent ? parent.replyId : "",
      ...otherparams,
    };
    let rule = this.itemsVO && this.itemsVO.isHideDelete === "1";
    if (this.page === "relatedToMe") {
      params = { ...params, menuType: "relatedme" };
    }
    return Api.coworkDiscussOperation(params).then((res) => {
      if (val === "delComment") {
        let params = {};
        if (rule || res.deleteType === 2) {
          if (
            res.replyList[0] &&
            res.replyList[0].childReply.length === 0 &&
            !this.detailHeader.canEdit
          ) {
            params = {
              replyId: parent.replyId,
              parentId: "",
              reply: res.replyList[0],
            };
          } else {
            params = {
              reply: res.replyList[0].childReply,
            };
          }
        }
        if (this.page === "relatedCommunication") {
          this.relatedComment.doOperateReply({
            replyId: data.replyId,
            parentId: parent ? parent.replyId : "",
            reply: res.replyList[0].childReply,
            ...params,
          });
        } else {
          this.relatedMeComment.doOperateReply({
            replyId: data.replyId,
            parentId: parent ? parent.replyId : "",
            //  reply: rule || res.deleteType === 2 ? null : res.replyList[0].childReply, // 1逻辑删除；2物理删除
            reply: res.replyList[0].childReply,
          });
        }

        if (!res.flag) {
          Bubble.error(getLabel("517403", "您无权限对当前评论做出操作"));
        }
      } else {
        if (this.page === "relatedCommunication") {
          if (!res.flag) {
            Bubble.error(
              getLabel("520107", "信息已超过可删除时间，或者您无操作权限")
            );
          } else {
            this.relatedComment.doOperateReply({
              replyId: data.replyId,
              parentId: parent ? parent.replyId : "",
              reply: res.replyList[0],
            });
          }
        } else {
          if (!res.flag) {
            Bubble.error(
              getLabel("520107", "信息已超过可删除时间，或者您无操作权限")
            );
          } else {
            this.relatedMeComment.doOperateReply({
              replyId: data.replyId,
              parentId: parent ? parent.replyId : "",
              reply: res.replyList[0],
            });
          }
        }
      }
      if (callback) callback();
    });
  };

  @action("评论提交事件")
  saveComment = (datas, callback) => {
    this.communicateReply.doClear(); // 发表完协作清除数据
    if (this.approvalAtatus === "1") {
      Bubble.error(getLabel(83249, "主题处于待审批状态禁止发言"));
    } else {
      if (this.replyComment) {
        this.replyType === "quote" &&
          this.quoteReplyStoreMap[this.replyComment.replyId].doClear();
        this.replyType === "comment" &&
          this.commentReplyStoreMap[this.replyComment.replyId].doClear();
      }
      //手机端发表图片往内容最后追加
      let remark = datas.text;
      let atList = datas.atList;
      this.imagrArr.forEach((item, index, array) => {
        remark = remark + item;
      });
      let params = {
        id: "",
        coworkId:
          (this.replyComment && this.replyComment.coworkId) || this.coworkId,
        remark: remark,
        relatedprj:
          (toJS(this.replyDatas).task &&
            toJS(this.replyDatas).task.map((item) => item.id)) ||
          "",
        relatedcus:
          (toJS(this.replyDatas).customer &&
            toJS(this.replyDatas).customer.map((item) => item.id)) ||
          "",
        relatedwf:
          (toJS(this.replyDatas).workFlow &&
            toJS(this.replyDatas).workFlow.map((item) => item.id)) ||
          "",
        relateddoc:
          (toJS(this.replyDatas).document &&
            toJS(this.replyDatas).document.map((item) => item.id)) ||
          "",
        relatedacc:
          (toJS(this.replyDatas).uploadFile &&
            toJS(this.replyDatas).uploadFile.map((item) => item.id)) ||
          "", // 附件
        projectIDs:
          (toJS(this.replyDatas).project &&
            toJS(this.replyDatas).project.map((item) => item.id)) ||
          "",
        replayid: this.replyComment ? this.replyComment.replyId : "",
        topdiscussid: this.replyComment
          ? this.replyCommentParent
            ? this.replyCommentParent.replyId
            : this.replyComment.replyId
          : "",
        isAnonymous: datas.checked ? "1" : "",
        replyType: this.replyComment ? this.replyType : "",
        delrelatedacc: "",
        atUserIds: (toJS(atList) && toJS(atList).map((item) => item.id)) || "",
      };
      if (this.page === "relatedToMe") {
        params = { ...params, menuType: "relatedme" };
      }
      return Api.submitCoworkDiscuss(params).then((res) => {
        if (res.flag) {
          if (this.replyComment) {
            if ("quote" === this.replyType) {
              this.relatedPage = 1;
              if (this.page === "relatedCommunication") {
                this.relatedComment.getDatas();
              } else {
                this.relatedMeComment.getDatas();
              }
              this.quoteReplyStoreMap[this.replyComment.replyId].doClear();
              this.imagrArr = [];
            } else {
              if (this.page === "relatedCommunication") {
                this.relatedComment.doOperateReply({
                  replyId: this.replyComment.replyId,
                  parentId: this.replyCommentParent
                    ? this.replyCommentParent.replyId
                    : "",
                  reply: this.replyCommentParent
                    ? res.replyList[0].childReply
                    : res.replyList[0],
                });
              } else {
                this.relatedMeComment.doOperateReply({
                  replyId: this.replyComment.replyId,
                  parentId: this.replyCommentParent
                    ? this.replyCommentParent.replyId
                    : "",
                  reply: this.replyCommentParent
                    ? res.replyList[0].childReply
                    : res.replyList[0],
                });
              }

              this.commentReplyStoreMap[this.replyComment.replyId].doClear();
              this.imagrArr = [];
            }
          } else {
            this.relatedPage = 1;
            if (this.page === "relatedCommunication") {
              this.relatedComment.getDatas();
            } else {
              this.relatedMeComment.getDatas();
            }
            this.imagrArr = [];
          }
          // this.replyVisible(false);
          this.outReplyVisible = true;
          this.communicateReplyVisible(false);
          this.replyType = "";
          this.replyDatas = {};
          if (callback) callback();
        } else {
          if (res.msg) {
            Bubble.error(res.msg);
          } else {
            Bubble.error(getLabel(30651, "操作失败"));
          }
        }
      });
    }
  };

  @action("发表协作交流")
  publishCowork = (datas) => {
    this.communicateReply.doClear(); // 发表完协作清除数据
    if (this.approvalAtatus === "1") {
      Bubble.error(getLabel(83249, "主题处于待审批状态禁止发言"));
    } else {
      //手机端发表图片往内容最后追加
      let remark = datas.text;
      let atList = datas.atList;
      this.imagrArr.forEach((item, index, array) => {
        remark = remark + item;
      });
      let params = {
        coworkId: this.coworkId,
        remark: remark,
        isAnonymous: datas.checked ? "1" : "",
        relatedprj:
          (toJS(this.replyDatas).task &&
            toJS(this.replyDatas).task.map((item) => item.id)) ||
          "",
        relatedcus:
          (toJS(this.replyDatas).customer &&
            toJS(this.replyDatas).customer.map((item) => item.id)) ||
          "",
        relatedwf:
          (toJS(this.replyDatas).workFlow &&
            toJS(this.replyDatas).workFlow.map((item) => item.id)) ||
          "",
        relateddoc:
          (toJS(this.replyDatas).document &&
            toJS(this.replyDatas).document.map((item) => item.id)) ||
          "",
        relatedacc:
          (toJS(this.replyDatas).uploadFile &&
            toJS(this.replyDatas).uploadFile.map((item) => item.id)) ||
          "", // 附件
        projectIDs:
          (toJS(this.replyDatas).project &&
            toJS(this.replyDatas).project.map((item) => item.id)) ||
          "",
        atUserIds: (toJS(atList) && toJS(atList).map((item) => item.id)) || "",
      };
      return Api.submitCoworkDiscuss(params).then((res) => {
        if (res.flag) {
          this.relatedPage = 1;
          if (this.page === "relatedCommunication") {
            this.relatedComment.getDatas();
          } else {
            this.relatedMeComment.getDatas();
          }
          this.communicateReplyVisible(false);
          this.imagrArr = [];
          this.replyDatas = {};
        } else {
          if (res.msg) {
            Bubble.error(res.msg);
          } else {
            Bubble.error(getLabel(30651, "操作失败"));
          }
        }
      });
    }
  };

  @action("标星操作")
  coworkMarkItemAsType = (val, id) => {
    let params = {
      coworkids: id ? id : this.coworkId,
      type: val,
    };
    Api.coworkMarkItemAsType(params).then((res) => {
      res.api_status && val === "normal"
        ? this.setStoreState({ isImportant: false })
        : this.setStoreState({ isImportant: true });
    });
  };

  @action("协作结束")
  batchCoworkItemMonitorEnd = () => {
    let params = {
      coworkIds: this.coworkId,
    };
    Api.batchCoworkItemMonitorEnd(params).then((res) => {
      const status = res.status;
      if (status === "1") {
        this.relatedPage = 1;
        this.page = "relatedCommunication";
        if (this.page === "relatedCommunication") {
          this.relatedComment.getDatas();
        } else {
          this.relatedMeComment.getDatas();
        }
        Bubble.success(getLabel(30700, "操作成功") + "!", 1);
        this.viewCowork();
      }
    });
  };

  @action("协作打开")
  coworkItemOperation = () => {
    let params = {
      coworkId: this.coworkId,
      operationType: "open",
    };
    Api.coworkItemOperation(params).then((res) => {
      const status = res.status;
      if (status === "1") {
        this.relatedPage = 1;
        this.page = "relatedCommunication";
        if (this.page === "relatedCommunication") {
          this.relatedComment.getDatas();
        } else {
          this.relatedMeComment.getDatas();
        }
        Bubble.success(getLabel(30700, "操作成功") + "!", 1);
        this.viewCowork();
      }
    });
  };

  @action("退出协作")
  quitCowork = (callback) => {
    let params = { coworkId: this.coworkId };
    Api.quitCowork(params).then((res) => {
      if (res.flag) {
        Bubble.success(getLabel("513434", "退出协作成功！"));
        if (callback) setTimeout(() => callback(), 1250);
      } else {
        let msg = getLabel("384402", "操作失败，请重试！");
        if (res.canQuit !== "1" && res.message) msg = res.message;
        Bubble.error(msg);
      }
    });
  };

  getIsCoworkHiddened = () => {
    return this.isCoworkHiddened;
  };
  /* **************************************** 与我相关 ************************************************ */
  @action("与我相关列表请求")
  relatedMe = () => {
    this.loading = true;
    const relatedAdSearchParams = this.relatedAdSearch.form.formParams || {};
    let params = {
      coworkId: this.coworkId,
      recordType: "relatedme",
      currentPage: this.relatedPage++,
      srchFloorNum: this.floor,
      isShowApproval: "",
      ...relatedAdSearchParams,
    };
    return Api.discussRecord(params).then((res) => {
      this.hasMore = res.hasMore;
      this.loading = false;
      return res;
    });
  };

  /* **************************************** 参与情况 ************************************************ */

  @action("参与情况")
  getShareConditionStrList = (val) => {
    let params = {
      coworkId: this.coworkId,
      type: val,
    };
    Api.getShareConditionStrList(params).then((res) => {
      this.partersMap = res;
    });
  };
  /* **************************************** 相关资源 ************************************************ */
  @action("相关资源")
  getCoworkDiscussData = () => {
    let params = {
      coworkId: this.coworkId,
    };
    Api.getCoworkDiscussData(params).then((res) => {
      this.resourceMap = res;
    });
  };

  getReplyAttachList = () => {
    let params = {
      routePath: this.routePath,
      typeId: this.itemsVO.typeid || "",
    };
    return Api.getCoworkAppStatus(params).then((res) => res);
  };

  @action
  getAttachList = () => {
    let params = { routePath: this.routePath, typeId: this.itemsVO.typeid };
    return Api.getCoworkAppStatus(params).then((res) => {
      return res;
    });
  };

  @action
  setRoutePath = (pathname) => {
    this.routePath = pathname;
  };

  // 组件卸载执行操作
  clearInfo = () => {
    this.detailHeader = {};
    this.hasMore = true;
    this.recordType = "common";
    this.relatedPage = 1;
    this.page = "relatedCommunication";
    this.floor = "";
    this.fixTop = false;
    this.index = 0;
    this.outReplyVisible = true;
    this.communicateReply.doClear();
    this.imagrArr = [];
    this.coworkText = ""; // 清空富文本内容
    this.replyType = "";
  };

  /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!    CreateStore   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
  @action createInital = (id) => {
    this.createRichText = new CKRichText.Store({
      reply: { getAttachList: () => this.getCreateAttachList() },
    });
    id
      ? this.coworkAddCondition({ id: id, type: "edit" })
      : this.coworkAddCondition();
    this.getNewMyCoworkTypeMapByMobile();
  };

  /* 基本信息Tab页面 */
  @action("初始化Form表单")
  coworkAddCondition = (params = {}) => {
    this.createLoading = true;
    Api.coworkAddCondition(params).then((res) => {
      this.addInfoForm.initForm(res.condition, this.createRoutePath);
      this.createLoading = false;
    });
  };

  @action("版块更新")
  getCoworkAccessory = (value) => {
    let params = {
      typeId: this.addInfoForm.formParams.typeId || this.typeId || "",
    };
    Api.getCoworkAccessory(params).then((res) => {
      if (res.status === "1") {
        /* 操作成功下的操作 */
        this.accessoryPath = res;
        this.uploadUrl = this.uploadUrl + "?secId=" + res.secId;
      } else {
        Bubble.error(
          getLabel(187, "读取协作附件失败, msg:", "error") + res.msg
        );
      }
    });
  };

  @action("更新结束时间")
  updateEndDate = (value) => {
    this.addInfoForm.updateField("endDate", value);
  };

  @action(
    "协作-新建协作版块类型切换，取对应版块的信息以及联调属性等（如是否可匿名）"
  )
  getNewMyCoworkTypeMapByMobile = () => {
    Api.getNewMyCoworkTypeMapByMobile().then((res) => {
      this.coworkTypeInfoMap = res.coworkTypeInfoMap;
    });
  };

  @action("提交操作")
  submitInfo = (callback) => {
    let validResult = this.addInfoForm.doValidate();
    if (validResult.pass) {
      this.createDisabled = true;
      this.baseSave("", callback);
    } else {
      Bubble.error(validResult.message);
      this.createPage === 1 &&
        this.setStoreState({ createPage: 0, topKey: "basic" });
    }
  };

  @action("新建保存协作")
  baseSave = (params, callback) => {
    let relatedid = "";
    params = {
      params,
      ...toJS(this.addInfoForm.formParams),
      operationType: "add",
      remark: this.coworkText,
      relatedPrj:
        (this.params_fileds.task &&
          this.params_fileds.task.map((item) => relatedid + item.id)) ||
        "", // 相关任务
      relatedCus:
        (this.params_fileds.customer &&
          this.params_fileds.customer.map((item) => relatedid + item.id)) ||
        "", // 相关客户
      relatedWf:
        (this.params_fileds.workFlow &&
          this.params_fileds.workFlow.map((item) => relatedid + item.id)) ||
        "", // 相关流程
      relatedDoc:
        (this.params_fileds.document &&
          this.params_fileds.document.map((item) => relatedid + item.id)) ||
        "", // 相关文档
      relatedAcc:
        (this.params_fileds.uploadFile &&
          this.params_fileds.uploadFile.map((item) => relatedid + item.id)) ||
        "", // 相关附件
      projectIds:
        (this.params_fileds.project &&
          this.params_fileds.project.map((item) => relatedid + item.id)) ||
        "", // 相关项目
    };
    Api.saveorupdateCoworkItemVo(params).then((res) => {
      if (res.status === "1") {
        Bubble.success(getLabel(30700, "操作成功") + "!", 1);
        this.itemsVo = res.coworkItemVoMap.itemsVO;
        this.editTypeId = res.coworkItemVoMap.itemsVO.typeid;
        if (callback) {
          setTimeout(() => {
            callback();
            this.createDisabled = false; // 跳转完后再置为false，如果改动跳转（不需要跳转）在清空表单后进行该项操作[因为有延时，会有一种视觉误差]
          }, 1000);
        } else {
          this.createDisabled = false;
          this.onClearFormData();
        }
      }
    });
  };

  // 有跳转的情况下不清空表单内容,为了处理视觉差效果
  @action onClearFormData = () => {
    this.addInfoForm.resetFields(); // 清空表单数据
    this.coworkText = ""; // 清空富文本内容
  };

  /* 详情说明 */
  @action("富文本内容更改触发方法")
  setCoworkText = (val) => {
    this.coworkText = val;
  };

  // 检测是否将自己移除了负责人
  @action onCheckPrincipal = async (callback) => {
    const formParams = this.addInfoForm.formParams;
    const params = {
      principal: formParams.principal,
      id: this.id,
    };
    const options = {
      method: "POST",
      url: "/api/cowork/base/judgeCoworkAuthorityChange",
      params,
    };
    let needChange = false;
    let res = await Tools.callApi(options);
    needChange = res.authorityChange;
    if (needChange) {
      alert(
        getLabel("524586", "保存后将失去对该主题的维护权限"),
        getLabel("524587", "确定要保存吗？"),
        [
          { text: getLabel(201, "取消") },
          { text: getLabel(826, "确定"), onPress: callback },
        ]
      );
    } else {
      callback && callback();
    }
  };

  /* 编辑 */
  @action("编辑保存")
  submitEditInfo = (callback) => {
    let validResult = this.addInfoForm.doValidate();
    if (validResult.pass) {
      this.onCheckPrincipal(() => {
        this.createDisabled = true;
        this.editSave(callback);
        this.relatedPage = 1;
      });
    } else {
      Bubble.error(validResult.message);
      this.relatedPage = 1;
      this.createPage = 0; // 当前Tab页指向
    }
  };

  @action("保存操作")
  editSave = (callback) => {
    let relatedid = "";
    let params = {
      ...toJS(this.addInfoForm.formParams),
      operationType: "edit",
      id: this.id,
      remark: this.coworkText, // 详细说明
      relatedPrj: this.params_fileds.task.map((item) => {
        return relatedid + item.id;
      }), // 相关任务
      relatedCus: this.params_fileds.customer.map((item) => {
        return relatedid + item.id;
      }), // 相关客户
      relatedWf: this.params_fileds.workFlow.map((item) => {
        return relatedid + item.id;
      }), // 相关流程
      relatedDoc: this.params_fileds.document.map((item) => {
        return relatedid + item.id;
      }), // 相关文档
      relatedAcc: this.params_fileds.uploadFile.map((item) => {
        return relatedid + item.id;
      }), // 相关附件
      projectIds: this.params_fileds.project.map((item) => {
        return relatedid + item.id;
      }), // 相关项目
    };

    Api.saveorupdateCoworkItemVo(params).then((res) => {
      if (res.status === "1" && res.flag !== false) {
        Bubble.success(getLabel(30700, "操作成功") + "!", 1);
        this.itemsVo = res.coworkItemVoMap.itemsVO;
        if (callback) callback();
        // 为了处理编辑完后重置表单视觉差，这边不清空表单
        // this.addInfoForm.resetFields(); // 清空表单数据
        this.createDisabled = false;
        this.createPage = 0; // 当前Tab页指向
        this.page = "relatedCommunication";
      }
    });
  };

  editClear = () => {
    this.coworkText = this.itemsVORemark;
    this.params_fileds = createParams.params_fileds;
  };

  @action
  getCreateAttachList = () => {
    let params = {
      routePath: this.createRoutePath,
      typeId: this.editTypeId,
      id: this.id,
    };
    return Api.getCoworkAppStatus(params).then((res) => {
      toJS(res.attachList).map((v) => {
        if (v.key === "uploadFile") {
          this.params_fileds[v.key] = v.config.datas;
        } else {
          this.params_fileds[v.key] = v.config.valueArray;
        }
      });
      return res;
    });
  };

  @action("组件卸载")
  clear = () => {
    this.addInfoForm.resetFields(); // 清空表单数据
    this.createPage = 0;
    this.params_fileds = createParams.params_fileds;
    this.atSomeOneDatas = [];
  };

  //关闭所有弹窗
  @action closeAllModel = () => {
    this.currentModel &&
      typeof this.currentModel.close === "function" &&
      this.currentModel.close();
  };
}
